package com.itheima.reggie.web;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDTO;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.ICategoryService;
import com.itheima.reggie.service.IDishFlavorService;
import com.itheima.reggie.service.IDishService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RequestMapping("/dish")
@RestController
public class DishController {
    @Autowired
    IDishService dishService;
    @Autowired
    ICategoryService categoryService;
    @Autowired
    IDishFlavorService dishFlavorService;
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 添加菜品
     * 注意点:表现层接收添加的菜品数据时,需要使用dishDTO类接收
     * @param dishDTO
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDTO dishDTO){
        log.info("save disDTO:{}",dishDTO);
        //添加dish表数据
        dishService.save(dishDTO);
        //添加dishFlavor数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        //判断是否选择口味
        if (flavors != null && flavors.size()>0){
            Long dishId = dishDTO.getId();
            for (DishFlavor flavor : flavors) {
                flavor.setDishId(dishId);
                dishFlavorService.save(flavor);
            }
        }
        //清理某个分类下面的菜品缓存数据
        String key = "dish_" + dishDTO.getCategoryId() ;
        redisTemplate.delete(key);
        return R.success("添加成功");
    }
    /**
     * 分页+条件查询菜品接口
     *
     * 注意点:封装的结果数据需要封装dishDTO
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(Integer page, Integer pageSize, String name){
        //用于查询dish分页数据
        Page<Dish> dishPage = new Page<>(page,pageSize);
        //构建条件查询器
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //设置查询条件
        dishLambdaQueryWrapper.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        //添加一个排序条件
        dishLambdaQueryWrapper.orderByDesc(Dish::getUpdateTime);
        //执行分页查询
        dishService.page(dishPage,dishLambdaQueryWrapper);
        //最终要返回给前端
        Page<DishDTO> dishDTOPage = new Page<>();

        //实现Page<Dish> 和 Page<DishDTO> 之间属性的对拷(拷贝)
        BeanUtils.copyProperties(dishPage,dishDTOPage,"records");
/*        //写法一
        List<DishDTO> dishDTOSList = new ArrayList<>();
        for (DishDTO dish : dishDTOSList) {//23条dish数据
            DishDTO dishDTO = new DishDTO();
            BeanUtils.copyProperties(dish,dishDTO);

            //查询菜品分类表
            Category category = categoryService.getById(dish.getCategoryId());
            dishDTO.setCategoryName(category.getName());

            dishDTOSList.add(dishDTO);
        }*/

        //写法er map接口
        List<DishDTO> dishDTOList = dishPage.getRecords().stream().map(dish -> {
            DishDTO dishDTO = new DishDTO();
            BeanUtils.copyProperties(dish, dishDTO);
            Category categoryId = categoryService.getById(dish.getCategoryId());
            dishDTO.setCategoryName(categoryId.getName());
            return dishDTO;
        }).collect(Collectors.toList());
        //将处理完毕后的dishDto集合封装到page对象中返回
        dishDTOPage.setRecords(dishDTOList);
        return R.success(dishDTOPage);
    }

    /**
     * 根据id查询菜品数据，用于回显
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDTO> queryOne(@PathVariable Long id){
        //1.查询dish表
        Dish dish = dishService.getById(id);
        DishDTO dishDTO = new DishDTO();
        BeanUtils.copyProperties(dish,dishDTO);
        //2.查询dish_flavor
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,id);
        List<DishFlavor> list = dishFlavorService.list(dishFlavorLambdaQueryWrapper);
        dishDTO.setFlavors(list);

        return R.success(dishDTO);

    }

    /**
     * 修改菜品
     * @param dishDTO
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDTO dishDTO){
        //1.修改菜品dish表的数据
        dishService.updateById(dishDTO);
        //2.删除dish关联的口味表中当前菜品的口味数据
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId,dishDTO.getId());
        dishFlavorService.remove(dishFlavorLambdaQueryWrapper);
        //3.添加菜品口味数据
        List<DishFlavor> flavors = dishDTO.getFlavors();
        List<DishFlavor> list = flavors.stream().map(dishFlavor -> {
            dishFlavor.setDishId(dishDTO.getId());
            return dishFlavor;
        }).collect(Collectors.toList());
        dishFlavorService.saveBatch(list);
        //清理所有菜品的缓存数据
        Set keys = redisTemplate.keys("dish_*"); //获取所有以dish_xxx开头的key
        redisTemplate.delete(keys); //删除这些key
        return R.success("修改成功");
    }

    /**
     * 删除菜品
     * 注意点:使用mybatis-plus提供的的逻辑删除
     * 1：删除  ， 0 ： 不删除
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> delete(@RequestParam List ids){
        //1.批量删除dish表中的数据
        dishService.removeByIds(ids);
        //2.批量删除当前菜品对应的口味表数据
        LambdaUpdateWrapper<DishFlavor> wrapper = new LambdaUpdateWrapper<>();
        //delete from dish_flavor where id in(?,?,?)
        wrapper.in(DishFlavor::getDishId,ids);
        dishFlavorService.remove(wrapper);

        //清空redis中缓存的指定分类下的菜品数据
        Set keys = redisTemplate.keys("dish_*"); //获取所有以dish_xxx开头的key
        redisTemplate.delete(keys); //删除这些key
        return R.success("删除成功");
    }

    @PostMapping("/status/{status}")
    public R<String> updateIds(@RequestParam List ids,@PathVariable Integer status){

        LambdaUpdateWrapper<Dish> dishLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        dishLambdaUpdateWrapper.set(Dish::getStatus,status).in(Dish::getId,ids);
        dishService.update(dishLambdaUpdateWrapper);
        return R.success("操作成功");
    }

    /**
     * 根据分类id查询该分类下的所有菜品集合
     * @param categoryId
     * @return
     */
    /**
     * 客户端主页面请求在此接口:
     *      完善的功能:查询并封装每一道菜品口味
     * @param categoryId
     * @param name
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDTO>> query(Long categoryId,String name){
        List<DishDTO> dishDTOList=null;
        //动态构造key
        String key = "dish_" + categoryId ;//dish_1397844391040167938_1
        //先从redis中获取缓存数据
        dishDTOList = (List<DishDTO>) redisTemplate.opsForValue().get(key);
        if(dishDTOList != null){
            //如果存在，直接返回，无需查询数据库
            return R.success(dishDTOList);
        }
        //redis中没有换成当前分类下的菜品数据,进行持久层操作,查询mysql中的分类下的菜品数据

        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(categoryId!=null,Dish::getCategoryId,categoryId);
        dishLambdaQueryWrapper.like(StringUtils.isNotEmpty(name),Dish::getName,name);
        dishLambdaQueryWrapper.eq(Dish::getStatus,1);
        dishLambdaQueryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        //2.查询菜品
        List<Dish> list = dishService.list(dishLambdaQueryWrapper);
        //3.封装分类名称
         dishDTOList = list.stream().map(item -> {
            DishDTO dishDTO = new DishDTO();
            BeanUtils.copyProperties(item, dishDTO);
            //3.1封装分类名称
            Long dishCategoryId = item.getCategoryId();
            //根据id查询分类对象
            Category category = categoryService.getById(dishCategoryId);
            if (category !=null){
                String categoryName = category.getName();
                dishDTO.setCategoryName(categoryName);
            }

            //查询菜品的口味数据
            List<DishFlavor> flavors = new ArrayList<>();
            LambdaQueryWrapper<DishFlavor> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(DishFlavor::getDishId, item.getId());
            flavors = dishFlavorService.list(queryWrapper);
            dishDTO.setFlavors(flavors);
            return dishDTO;
        }).collect(Collectors.toList());
        //如果不存在，需要查询数据库，将查询到的菜品数据缓存到Redis
        redisTemplate.opsForValue().set(key,dishDTOList,60, TimeUnit.MINUTES);
        return R.success(dishDTOList);
    }


}
